<template>
  <div class="history-data-query">
    <!-- 顶部搜索操作区 -->
    <div class="search-panel">
      <el-card>
        <el-form :model="searchForm" :inline="true" class="search-form">
          <!-- 设施范围 -->
          <el-form-item label="设施范围">
            <el-cascader v-model="searchForm.facilityIds" :options="facilityTree" :props="facilityProps"
              placeholder="请选择设施" style="width: 300px" :show-all-levels="false" clearable filterable multiple
              collapse-tags />
          </el-form-item>

          <!-- 监测量类型 -->
          <el-form-item label="监测量类型">
            <el-select v-model="searchForm.typeCategories" placeholder="监测量分类" multiple collapse-tags
              style="width: 200px" @change="onTypeCategoryChange">
              <el-option v-for="category in typeCategories" :key="category" :label="category" :value="category" />
            </el-select>
            <el-select v-model="searchForm.monitoringTypeIds" placeholder="具体监测量" multiple collapse-tags filterable
              style="width: 250px; margin-left: 8px">
              <el-option v-for="type in filteredMonitoringTypes" :key="type.paramId"
                :label="`${type.paramName} (${type.paramUnit})`" :value="type.paramId" />
            </el-select>
          </el-form-item>

          <!-- 数据精度 -->
          <el-form-item label="数据精度">
            <el-select v-model="searchForm.dataAccuracy" placeholder="时间粒度" style="width: 120px">
              <el-option label="1分钟" value="1分钟" />
              <el-option label="5分钟" value="5分钟" />
              <el-option label="15分钟" value="15分钟" />
              <el-option label="1小时" value="1小时" />
              <el-option label="1天" value="1天" />
            </el-select>
          </el-form-item>

          <!-- 时间范围 -->
          <el-form-item label="时间范围">
            <el-radio-group v-model="quickTimeType" @change="onQuickTimeChange" size="small">
              <el-radio-button label="today">今日</el-radio-button>
              <el-radio-button label="yesterday">昨日</el-radio-button>
              <el-radio-button label="last7days">近7天</el-radio-button>
              <el-radio-button label="last30days">近30天</el-radio-button>
            </el-radio-group>
            <el-date-picker v-model="timeRange" type="datetimerange" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="x" :default-time="defaultTime"
              @change="onTimeRangeChange" style="margin-left: 8px; width: 360px" />
          </el-form-item>

          <!-- 数据状态 -->
          <el-form-item label="数据状态">
            <el-select v-model="searchForm.dataStatus" placeholder="全部状态" clearable style="width: 120px">
              <el-option label="正常" :value="1" />
              <el-option label="异常" :value="2" />
              <el-option label="待验证" :value="3" />
            </el-select>
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon>
                <Refresh />
              </el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 操作按钮区 -->
        <div class="action-buttons">
          <el-button @click="handleExport" :loading="exportLoading">
            <el-icon>
              <Download />
            </el-icon>
            导出
          </el-button>
          <el-button @click="handleRefresh">
            <el-icon>
              <RefreshRight />
            </el-icon>
            刷新
          </el-button>
          <el-button @click="toggleChartVisible">
            <el-icon>
              <TrendCharts />
            </el-icon>
            {{ chartVisible ? '隐藏图表' : '显示图表' }}
          </el-button>
          <el-button @click="handleColumnSettings">
            <el-icon>
              <Setting />
            </el-icon>
            列设置
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 图表展示区 -->
    <div class="chart-panel" v-if="chartVisible && trendData.length > 0">
      <el-card>
        <template #header>
          <div class="chart-header">
            <h3>趋势分析</h3>
            <div class="chart-actions">
              <el-radio-group v-model="chartType" size="small">
                <el-radio-button label="line">折线图</el-radio-button>
                <el-radio-button label="bar">柱状图</el-radio-button>
              </el-radio-group>
              <el-button size="small" @click="exportChart">导出图表</el-button>
            </div>
          </div>
        </template>
        <div ref="chartRef" class="trend-chart" style="width: 100%; height: 300px;"></div>
      </el-card>
    </div>

    <!-- 中间列表区 -->
    <div class="table-panel">
      <el-card>
        <template #header>
          <div class="table-header">
            <span>历史数据列表</span>
            <div class="table-info">
              <span>共 {{ total }} 条记录</span>
            </div>
          </div>
        </template>

        <el-table :data="tableData" stripe style="width: 100%" v-loading="loading"
          @selection-change="handleSelectionChange" @sort-change="handleSortChange" :row-class-name="getRowClassName">
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />

          <el-table-column prop="collectionTime" label="采集时间" width="180" sortable="custom">
            <template #default="{ row }">
              {{ formatDate(row.collectionTime, 'yyyy-MM-dd HH:mm:ss') }}
            </template>
          </el-table-column>

          <el-table-column prop="facilityName" label="设施名称" width="150" show-overflow-tooltip />
          <el-table-column prop="processUnit" label="工艺单元" width="120" />
          <el-table-column prop="monitoringTypeName" label="监测量名称" width="150" />

          <el-table-column prop="monitoringValue" label="监测值" width="120" sortable="custom">
            <template #default="{ row }">
              <span :class="getValueClass(row)">
                {{ row.monitoringValue }} {{ row.unit }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="unit" label="单位" width="80" />

          <el-table-column prop="dataStatus" label="数据状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.dataStatus)" size="small" effect="light">
                {{ getStatusText(row.dataStatus) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="collectionDeviceId" label="采集设备" width="140" />
          <el-table-column prop="facilityLocation" label="安装位置" min-width="150" show-overflow-tooltip />
          <el-table-column prop="dataAccuracy" label="数据精度" width="100" />

          <el-table-column label="操作" width="80" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleDetail(row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <div class="pagination-panel">
          <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-card>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="数据详情" width="600px">
      <div v-if="selectedRow" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="采集时间">
            {{ formatDate(selectedRow.collectionTime, 'yyyy-MM-dd HH:mm:ss') }}
          </el-descriptions-item>
          <el-descriptions-item label="设施名称">
            {{ selectedRow.facilityName }}
          </el-descriptions-item>
          <el-descriptions-item label="工艺单元">
            {{ selectedRow.processUnit }}
          </el-descriptions-item>
          <el-descriptions-item label="安装位置">
            {{ selectedRow.facilityLocation }}
          </el-descriptions-item>
          <el-descriptions-item label="监测量名称">
            {{ selectedRow.monitoringTypeName }}
          </el-descriptions-item>
          <el-descriptions-item label="监测值">
            <span :class="getValueClass(selectedRow)">
              {{ selectedRow.monitoringValue }} {{ selectedRow.unit }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="数据状态">
            <el-tag :type="getStatusTagType(selectedRow.dataStatus)" effect="light">
              {{ getStatusText(selectedRow.dataStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="正常范围">
            {{ selectedRow.standardMin }} - {{ selectedRow.standardMax }} {{ selectedRow.unit }}
          </el-descriptions-item>
          <el-descriptions-item label="采集设备">
            {{ selectedRow.collectionDeviceId }}
          </el-descriptions-item>
          <el-descriptions-item label="数据精度">
            {{ selectedRow.dataAccuracy }}
          </el-descriptions-item>
          <el-descriptions-item label="入库时间">
            {{ formatDate(selectedRow.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDate(selectedRow.updateTime) }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 趋势图表 -->
        <div class="detail-chart" v-if="detailTrendData.length > 0">
          <el-divider>近1小时趋势</el-divider>
          <div ref="detailChartRef" style="width: 100%; height: 200px;"></div>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 导出设置弹窗 -->
    <el-dialog v-model="exportDialogVisible" title="导出设置" width="500px">
      <el-form :model="exportForm" label-width="100px">
        <el-form-item label="导出范围">
          <el-radio-group v-model="exportForm.exportType">
            <el-radio label="current">当前页数据</el-radio>
            <el-radio label="all">全部数据</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文件格式">
          <el-radio-group v-model="exportForm.fileFormat">
            <el-radio label="excel">Excel</el-radio>
            <el-radio label="csv">CSV</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="包含字段">
          <el-checkbox-group v-model="exportForm.selectedFields">
            <el-checkbox label="collectionTime">采集时间</el-checkbox>
            <el-checkbox label="facilityName">设施名称</el-checkbox>
            <el-checkbox label="monitoringTypeName">监测量名称</el-checkbox>
            <el-checkbox label="monitoringValue">监测值</el-checkbox>
            <el-checkbox label="unit">单位</el-checkbox>
            <el-checkbox label="dataStatus">数据状态</el-checkbox>
            <el-checkbox label="collectionDeviceId">采集设备</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="exportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmExport" :loading="exportLoading">
          确认导出
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Download,
  RefreshRight,
  TrendCharts,
  Setting
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {
  queryHistoryData,
  getTrendData,
  getFacilityTree,
  getTypeCategories,
  exportHistoryData,
  getParams
} from '@/api/prod_operate/prod_run/measurement_analysis'
import { formatDate, getQuickTimeRange } from '@/utils/date'

// 响应式数据
const loading = ref(false)
const exportLoading = ref(false)
const chartVisible = ref(true)

// 搜索表单
const searchForm = reactive({
  facilityIds: [],
  typeCategories: [],
  monitoringTypeIds: [],
  dataAccuracy: '15分钟',
  dataStatus: null
})

const quickTimeType = ref('last7days')
const timeRange = ref([])
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 1, 1, 23, 59, 59)
]

// 分页
const pagination = reactive({
  pageNum: 1,
  pageSize: 10
})
const total = ref(0)

// 表格数据
const tableData = ref([])
const selectedRows = ref([])
const trendData = ref([])

// 基础数据
const facilityTree = ref([])
const facilityProps = {
  value: 'facilityId',
  label: 'facilityName',
  children: 'children',
  multiple: true
}
const typeCategories = ref([])
const allMonitoringTypes = ref([])
const filteredMonitoringTypes = ref([])

// 图表相关
const chartRef = ref()
const detailChartRef = ref()
const chartType = ref('line')
let chartInstance = null
let detailChartInstance = null

// 对话框控制
const detailDialogVisible = ref(false)
const exportDialogVisible = ref(false)
const selectedRow = ref(null)
const detailTrendData = ref([])

// 导出表单
const exportForm = reactive({
  exportType: 'current',
  fileFormat: 'excel',
  selectedFields: ['collectionTime', 'facilityName', 'monitoringTypeName', 'monitoringValue', 'unit', 'dataStatus']
})

// 初始化
onMounted(() => {
  initData()
  initCharts()
  initTimeRange()
  handleSearch() // 默认查询
})

// 初始化数据
const initData = async () => {
  try {
    await loadFacilityTree()
    await loadTypeCategories()
    await loadMonitoringTypes()
  } catch (error) {
    ElMessage.error('基础数据加载失败')
  }
}

// 加载设施树
const loadFacilityTree = async () => {
  const res = await getFacilityTree()
  if (res.success) {
    // 构建树形结构
    const treeMap = {}
    const rootNodes = []

    res.data.forEach(item => {
      treeMap[item.facilityId] = {
        ...item,
        children: []
      }
    })

    res.data.forEach(item => {
      if (item.parentId && treeMap[item.parentId]) {
        treeMap[item.parentId].children.push(treeMap[item.facilityId])
      } else {
        rootNodes.push(treeMap[item.facilityId])
      }
    })

    facilityTree.value = rootNodes
  }
}

// 加载监测量分类
const loadTypeCategories = async () => {
  const res = await getTypeCategories()
  if (res.success) {
    typeCategories.value = res.data
  }
}

// 加载所有监测量类型
const loadMonitoringTypes = async () => {
  const res = await getParams()
  if (res.success) {
    allMonitoringTypes.value = res.data
    filteredMonitoringTypes.value = res.data
  }
}

// 初始化时间范围
const initTimeRange = () => {
  const range = getQuickTimeRange(quickTimeType.value)
  timeRange.value = [range.startTime, range.endTime]
}

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    if (chartRef.value) {
      chartInstance = echarts.init(chartRef.value)
    }
    if (detailChartRef.value) {
      detailChartInstance = echarts.init(detailChartRef.value)
    }
    window.addEventListener('resize', handleResize)
  })
}

// 处理窗口大小变化
const handleResize = () => {
  chartInstance?.resize()
  detailChartInstance?.resize()
}

// 监测量分类变化
const onTypeCategoryChange = (categories) => {
  if (categories.length === 0) {
    filteredMonitoringTypes.value = allMonitoringTypes.value
  } else {
    filteredMonitoringTypes.value = allMonitoringTypes.value.filter(
      type => categories.includes(type.typeCategory)
    )
  }
  searchForm.monitoringTypeIds = []
}

// 时间筛选变化
const onQuickTimeChange = () => {
  initTimeRange()
}

const onTimeRangeChange = () => {
  quickTimeType.value = ''
}

// 处理级联选择器的值：将路径数组转换为ID数组
const processFacilityIds = (facilityIds) => {
  if (!facilityIds || facilityIds.length === 0) {
    return []
  }
  // 级联选择器多选时返回的是路径数组的数组，需要提取最后一个值
  const result = []
  facilityIds.forEach(path => {
    if (Array.isArray(path)) {
      // 路径数组，取最后一个值
      if (path.length > 0) {
        result.push(path[path.length - 1])
      }
    } else {
      // 直接是字符串
      result.push(path)
    }
  })
  return result
}

// 搜索查询
const handleSearch = async () => {
  if (!timeRange.value || timeRange.value.length !== 2) {
    ElMessage.warning('请选择时间范围')
    return
  }

  loading.value = true
  try {
    // 处理级联选择器的值
    const processedFacilityIds = processFacilityIds(searchForm.facilityIds)
    
    const params = {
      ...searchForm,
      facilityIds: processedFacilityIds,
      startTime: timeRange.value[0],
      endTime: timeRange.value[1],
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      _t: Date.now() // 添加时间戳，确保每次请求参数不同，避免防重复提交误判
    }

    // 查询表格数据
    const res = await queryHistoryData(params)
    // 兼容不同的响应格式：{ success: true, data: [] } 或 { code: 200, data: { data: [], total: 0 } }
    let responseData = res
    if (res && res.code === 200 && res.data) {
      // 标准格式：{ code: 200, data: { data: [], total: 0 } }
      responseData = res.data
    }
    
    if (responseData && (responseData.success || res?.code === 200)) {
      tableData.value = responseData.data || []
      total.value = responseData.total || 0

      // 查询趋势数据
      if (searchForm.monitoringTypeIds && searchForm.monitoringTypeIds.length > 0) {
        try {
          const trendRes = await getTrendData({
            facilityIds: processedFacilityIds,
            monitoringTypeIds: searchForm.monitoringTypeIds,
            startTime: timeRange.value[0],
            endTime: timeRange.value[1]
          })
          // 兼容不同的响应格式
          let trendDataRes = trendRes
          if (trendRes && trendRes.code === 200 && trendRes.data) {
            trendDataRes = trendRes.data
          }
          if (trendDataRes && (trendDataRes.success || trendRes?.code === 200)) {
            trendData.value = trendDataRes.data || []
            renderTrendChart(trendDataRes.data || [])
          }
        } catch (trendError) {
          // 趋势数据查询失败不影响主查询
          console.warn('趋势数据查询失败:', trendError)
          trendData.value = []
          chartInstance?.clear()
        }
      } else {
        trendData.value = []
        chartInstance?.clear()
      }
    } else {
      // 响应不成功，显示错误信息（但不要显示防重复提交的错误）
      const errorMsg = res?.message || responseData?.message || '查询失败'
      if (errorMsg && !errorMsg.includes('重复提交')) {
        ElMessage.error(errorMsg)
      }
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('查询失败:', error)
    // 如果是防重复提交的错误，不显示错误提示（因为数据可能已经成功返回）
    const errorMsg = error?.response?.data?.message || error?.message || ''
    if (errorMsg && !errorMsg.includes('重复提交')) {
      ElMessage.error(errorMsg || '查询失败，请稍后重试')
    }
    // 即使有错误，也尝试从响应中获取数据（如果请求实际成功了）
    if (error?.response?.data && (error.response.data.success || error.response.data.code === 200)) {
      const errorResData = error.response.data
      const data = errorResData.data || (errorResData.code === 200 ? errorResData.data?.data : null)
      const totalCount = errorResData.total || (errorResData.code === 200 ? errorResData.data?.total : 0)
      if (data) {
        tableData.value = Array.isArray(data) ? data : []
        total.value = totalCount || 0
        return // 数据已成功获取，不需要显示错误
      }
    }
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 渲染趋势图表
const renderTrendChart = (data) => {
  if (!chartInstance || !data.length) return

  // 按设施和监测量分组数据
  const seriesMap = {}
  const timeSet = new Set()

  data.forEach(item => {
    const key = `${item.facilityName}-${item.monitoringTypeName}`
    const timeKey = formatDate(item.collectionTime, 'MM-dd HH:mm')

    if (!seriesMap[key]) {
      seriesMap[key] = {
        name: key,
        type: chartType.value,
        data: [],
        symbol: item.dataStatus === 2 ? 'circle' : 'none',
        symbolSize: item.dataStatus === 2 ? 4 : 0
      }
    }

    timeSet.add(timeKey)
  })

  // 构建时间轴
  const timeArray = Array.from(timeSet).sort()

  // 填充数据
  timeArray.forEach(time => {
    Object.keys(seriesMap).forEach(key => {
      const [facilityName, monitoringTypeName] = key.split('-')
      const item = data.find(d =>
        formatDate(d.collectionTime, 'MM-dd HH:mm') === time &&
        d.facilityName === facilityName &&
        d.monitoringTypeName === monitoringTypeName
      )
      seriesMap[key].data.push(item ? item.monitoringValue : null)
    })
  })

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let result = `${params[0].axisValue}<br/>`
        params.forEach(param => {
          const item = data.find(d =>
            formatDate(d.collectionTime, 'MM-dd HH:mm') === params[0].axisValue &&
            `${d.facilityName}-${d.monitoringTypeName}` === param.seriesName
          )
          const status = item?.dataStatus === 2 ? '（异常）' : ''
          result += `${param.seriesName}: ${param.value}${status}<br/>`
        })
        return result
      }
    },
    legend: {
      data: Object.keys(seriesMap),
      type: 'scroll',
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        restore: {},
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: chartType.value === 'line',
      data: timeArray
    },
    yAxis: {
      type: 'value'
    },
    series: Object.values(seriesMap)
  }

  chartInstance.setOption(option, true)
}

// 重置搜索条件
const handleReset = () => {
  searchForm.facilityIds = []
  searchForm.typeCategories = []
  searchForm.monitoringTypeIds = []
  searchForm.dataAccuracy = '15分钟'
  searchForm.dataStatus = null
  quickTimeType.value = 'last7days'
  initTimeRange()
  pagination.pageNum = 1
  pagination.pageSize = 10
}

// 刷新数据
const handleRefresh = () => {
  handleSearch()
}

// 切换图表显示
const toggleChartVisible = () => {
  chartVisible.value = !chartVisible.value
  if (chartVisible.value) {
    nextTick(() => {
      chartInstance?.resize()
    })
  }
}

// 列设置
const handleColumnSettings = () => {
  ElMessage.info('列设置功能开发中')
}

// 分页大小变化
const handleSizeChange = (size) => {
  // 由于使用了 v-model:page-size，值已经自动更新，只需要重置页码并查询
  pagination.pageNum = 1
  handleSearch()
}

// 当前页变化
const handleCurrentChange = (page) => {
  // 由于使用了 v-model:current-page，值已经自动更新，直接查询即可
  handleSearch()
}

// 表格行选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 排序变化
const handleSortChange = ({ column, prop, order }) => {
  ElMessage.info(`按 ${prop} ${order === 'ascending' ? '升序' : '降序'} 排序`)
  // 实际项目中这里应该重新请求排序后的数据
}

// 获取行样式
const getRowClassName = ({ row }) => {
  if (row.dataStatus === 2) return 'abnormal-row'
  if (row.dataStatus === 3) return 'pending-row'
  return ''
}

// 获取数值样式
const getValueClass = (row) => {
  if (row.dataStatus === 2) return 'abnormal-value'
  if (row.dataStatus === 3) return 'pending-value'
  return 'normal-value'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 1: return 'success'
    case 2: return 'danger'
    case 3: return 'warning'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1: return '正常'
    case 2: return '异常'
    case 3: return '待验证'
    default: return '未知'
  }
}

// 查看详情
const handleDetail = async (row) => {
  selectedRow.value = row
  detailDialogVisible.value = true

  // 加载详情趋势数据
  try {
    const oneHourAgo = new Date(row.collectionTime).getTime() - 60 * 60 * 1000
    const trendRes = await getTrendData({
      facilityIds: [row.facilityId],
      monitoringTypeIds: [row.monitoringTypeId],
      startTime: oneHourAgo,
      endTime: new Date(row.collectionTime).getTime()
    })
    if (trendRes.success) {
      detailTrendData.value = trendRes.data
      nextTick(() => {
        renderDetailChart(trendRes.data)
      })
    }
  } catch (error) {
    console.error('加载详情趋势数据失败:', error)
  }
}

// 渲染详情图表
const renderDetailChart = (data) => {
  if (!detailChartInstance || !data.length) return

  const timeArray = data.map(item => formatDate(item.collectionTime, 'HH:mm:ss'))
  const valueArray = data.map(item => item.monitoringValue)

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: timeArray
    },
    yAxis: {
      type: 'value',
      name: selectedRow.value?.unit
    },
    series: [{
      data: valueArray,
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        width: 2
      }
    }]
  }

  detailChartInstance.setOption(option, true)
}

// 导出数据
const handleExport = () => {
  exportDialogVisible.value = true
}

const confirmExport = async () => {
  exportLoading.value = true
  try {
    // 处理级联选择器的值
    const processedFacilityIds = processFacilityIds(searchForm.facilityIds)
    
    const params = {
      ...searchForm,
      facilityIds: processedFacilityIds,
      startTime: timeRange.value[0],
      endTime: timeRange.value[1],
      exportType: exportForm.exportType,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    }

    const res = await exportHistoryData(params)
    if (res && res.success) {
      ElMessage.success(`导出成功，共 ${res.count || 0} 条数据`)
      exportDialogVisible.value = false

      // 实际项目中这里应该下载文件
      console.log('导出数据:', res.data)
    } else {
      const errorMsg = res?.message || '导出失败'
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error(error?.response?.data?.message || error?.message || '导出失败，请稍后重试')
  } finally {
    exportLoading.value = false
  }
}

// 导出图表
const exportChart = () => {
  if (chartInstance) {
    const chartDataURL = chartInstance.getDataURL({
      type: 'png',
      pixelRatio: 2,
      backgroundColor: '#fff'
    })
    const link = document.createElement('a')
    link.href = chartDataURL
    link.download = '历史数据趋势图.png'
    link.click()
  }
}

// 监听图表类型变化
watch(chartType, () => {
  if (trendData.value.length > 0) {
    renderTrendChart(trendData.value)
  }
})

// 移除分页监听，避免重复调用
// watch([() => pagination.pageNum, () => pagination.pageSize], () => {
//   handleSearch()
// })

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chartInstance?.dispose()
  detailChartInstance?.dispose()
})
</script>

<style scoped>
.history-data-query {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.search-panel {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: flex-start;
}

.action-buttons {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  border-top: 1px solid #e4e7ed;
  padding-top: 16px;
}

.chart-panel {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.trend-chart {
  margin-top: 16px;
}

.table-panel {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-panel {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.detail-content {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-chart {
  margin-top: 20px;
}

/* 表格行样式 */
:deep(.abnormal-row) {
  background-color: #fef0f0 !important;
}

:deep(.pending-row) {
  background-color: #fdf6ec !important;
}

.abnormal-value {
  color: #f56c6c;
  font-weight: bold;
}

.pending-value {
  color: #e6a23c;
  font-weight: bold;
}

.normal-value {
  color: #67c23a;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .search-form .el-form-item {
    margin-right: 0;
  }
}
</style>